package com.yangyang.androidconnect.common;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class NetworkUtils {

    private static final String TAG = "NetworkUtils";

    public static List<String> getIPv4Address(Context context) {
        List<String> ipList = new LinkedList<>();
        StringBuilder ipAddresses = new StringBuilder();
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface networkInterface : Collections.list(interfaces)) {
                // 跳过未启用或回环接口
                if (!networkInterface.isUp() || networkInterface.isLoopback()) {
                    continue;
                }

                // 遍历接口的所有地址
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                String interfaceName = networkInterface.getName();
                String displayName = networkInterface.getDisplayName();
                for (InetAddress address : Collections.list(addresses)) {
                    // 只处理IPv4地址
                    if (address instanceof java.net.Inet4Address) {
                        String hostAddress = address.getHostAddress();
                        ipAddresses.append(hostAddress).append("\n");
                        ipList.add(hostAddress);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果结果不为空，返回IPv4地址列表
        if (ipAddresses.length() > 0) {
            //return ipAddresses.toString().trim();
            return ipList;
        }

        // 如果未获取到地址，尝试从Wi-Fi获取
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            if (ipAddress != 0) {
                String formatIPAddress = formatIPAddress(ipAddress);
                ipList.add(formatIPAddress);
                //return formatIPAddress;
                return ipList;
            }
        }

        //return "Unable to retrieve IP address";
        return ipList;
    }


    // 获取所有IPv6地址
    public static String getAllIPv6Addresses(Context context) {
        StringBuilder ipv6Addresses = new StringBuilder();

        try {
            // 遍历所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface networkInterface : Collections.list(interfaces)) {
                // 跳过未启用或回环接口
                if (!networkInterface.isUp() || networkInterface.isLoopback()) {
                    continue;
                }

                // 遍历接口的所有地址
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                String interfaceName = networkInterface.getName();
                String displayName = networkInterface.getDisplayName();
                for (InetAddress address : Collections.list(addresses)) {
                    // 只处理IPv6地址
                    if (address instanceof java.net.Inet6Address) {
                        String addressString = address.getHostAddress();
                        // 去除IPv6地址中可能存在的'%'符号部分
                        int index = addressString.indexOf('%');
                        if (index != -1) {
                            addressString = addressString.substring(0, index);
                        }
                        ipv6Addresses.append(addressString).append("\n");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果结果不为空，返回IPv6地址列表
        if (ipv6Addresses.length() > 0) {
            return ipv6Addresses.toString().trim();
        }

        return "Unable to retrieve IPv6 address";
    }


    public static List<String> getIPv6Addresses() {
        List<String> ipv6Addresses = new ArrayList<>();
        try {
            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                    if (inetAddress instanceof Inet6Address) {
                        String address = inetAddress.getHostAddress();
                        int index = address.indexOf('%');
                        if (index != -1) {
                            address = address.substring(0, index);
                        }
                        ipv6Addresses.add(address);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting IPv6 addresses: " + e.getMessage());
        }
        return ipv6Addresses;
    }


    public static String getWlanIPv6Addresses(Context context) {
        try {
            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                if (isWifiInterface(networkInterface)) {
                    for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                        if (inetAddress instanceof Inet6Address) {
                            String address = inetAddress.getHostAddress();
                            int index = address.indexOf('%');
                            if (index != -1) {
                                address = address.substring(0, index);
                            }
                            return address;
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting IPv6 addresses: " + e.getMessage());
        }
        return null;
    }

    private static boolean isWifiInterface(NetworkInterface networkInterface) {
        // You can customize this method to identify WiFi interfaces based on your requirements
        // For example, by checking interface name, flags, or other characteristics
        // Here's a simple example assuming WiFi interface names start with "wlan"
        return networkInterface.getName().startsWith("wlan");
    }


    private static String formatIPAddress(int ipAddress) {
        return ((ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                ((ipAddress >> 24) & 0xFF));
    }
}
